import Router from "koa-router";
import type Koa from "koa";
import { cwd } from 'node:process';
import fs from 'fs';
import { Api } from "../type";

export const authRouter = async (app: Koa<Koa.DefaultState, Koa.DefaultContext>) => {
    const path = cwd() + '/src/api'
    const router = new Router()
    const getFileList = (path: string): Promise<string[]> => {
        return new Promise((res, rej) => {
            fs.readdir(path, (err, data) => {
                if (err) rej(err)
                else res(data)
            })
        })
    }
    const fun = async (path: string) => {
        const list = await getFileList(path)
        await Promise.all(list.map(async url => {
            const P = path + '/' + url
            const prefix = P.replace(cwd() + '/src', '').replace('.ts', '')
            if (/.ts/.test(url)) {
                const res = await import(P)
                const map = res.router as Api
                if (!(map instanceof Map)) return
                map.forEach((value, key) => {
                    if (Array.isArray(key)) {
                        const url = prefix + key[0]
                        if (Array.isArray(value))
                            router[key[1]](url, ...value)
                        else
                            router[key[1]](url, value)
                    } else {
                        const url = prefix + key
                        if (Array.isArray(value))
                            router.post(url, ...value)
                        else
                            router.post(url, value)
                    }
                })
            }
            else if (/.js/.test(url)) { }
            else {
                return await fun(P)
            }
        }))
    }
    await fun(path)
    app.use(router.routes())
}